<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category Stock.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/7/5  15:02
 * +--------------------------------------------------------+
 */

namespace App\Util;


use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;

class Stock
{

    /**
     * @return array|mixed
     * @Depiction 获取市场数据
     * @Author hwy <429208948@qq.com>
     * @Date 2022/7/5  15:04
     */
    public function getMarketData()
    {
        $url  = 'https://stock.zsxg.cn/api/v2/capital/marketSummary';
        $data = curl($url);
        $data = json_decode($data, true);
        $data = $data['datas'] ?? [];

        if(empty($data)){
            return $data;
        }

        // 资金列表
        $amountList = $data['amountList'] ?? [];

        // 涨跌
        $chg = $data['chg'] ?? 0;

        // 中位数涨跌
        $medChgData  = $data['medChg'] ?? 0;
        $medChgHashs = $data['medChgHash'] ?? [];
        ksort($medChgHashs);
        $date   = [];
        $medChg = [];
        foreach ($medChgHashs as $key => $medChgHash) {
            $date[]   = $key;
            $medChg[] = $medChgHash;
        }
        $res_medChgHash = [
            'dateData'   => $date,
            'medChgData' => $medChg,
        ];

        $rise_fall_stat = $data['rise_fall_stat'] ?? []; //f:跌 p：平 r:涨  list temp

        $stockTotalNum = $data['stockTotalNum'] ?? 0;
        $stockTodayNum = $data['stockTodayNum'] ?? 0;
        $tradeAmount   = $data['tradeAmount'] ?? 0;

        if ($chg > 2) {
            $res_chgMsg = '极好';
            $res_chgImg = 'images/chgImg1.png';
        } elseif ($chg > 1) {
            $res_chgMsg = '很好';
            $res_chgImg = 'images/chgImg1.png';
        } elseif ($chg > 0) {
            $res_chgMsg = '好';
            $res_chgImg = 'images/chgImg2.png';
        } elseif ($chg > -1) {
            $res_chgMsg = '差';
            $res_chgImg = 'images/chgImg3.png';
        } elseif ($chg > -2) {
            $res_chgMsg = '很差';
            $res_chgImg = 'images/chgImg3.png';
        } else {
            $res_chgMsg = '急差';
            $res_chgImg = 'images/chgImg3.png';
        }

        $dateAmount = [];
        $amountData = [];
        $absData    = [];
        foreach ($amountList as $k => $amounts) {
            $dateAmount[] = date("m-d", strtotime($amounts['date']));
            $amountData[] = sprintf("%.2f", round($amounts['amount'] / 1000000000, 2));
            if ($amounts['chg'] > 0) {
                $absData[] = 1;
            } else {
                $absData[] = -1;
            }
        }
        $res_amountList = [
            'dateAmount' => $dateAmount,
            'amountData' => $amountData,
            'absData'    => $absData,
        ];

        $rateRiseFall     = [];
        $riseFallData     = [];
        $res_riseFallStat = [
            'riseFallData' => $rise_fall_stat['list'] ?? [],
            'dateRiseFall' => ['跌停', '>7', '4-7', '2-4', '0-2', '平', '0-2', '2-4', '4-7', '>7', '涨停'],
        ];


        $res['chg']          = sprintf("%.2f", round($chg, 2));
        $res['medChg']       = sprintf("%.2f", round($medChgData, 2));
        $res['medChgHash']   = $res_medChgHash;
        $res['tradeAmount']  = sprintf("%.4f", round($tradeAmount / 1000000000, 4)) . '万亿';
        $res['amountList']   = $res_amountList;
        $res['chgImg']       = $res_chgImg;
        $res['chgMsg']       = $res_chgMsg;
        $res['riseFallStat'] = $res_riseFallStat;
        $res['rise']         = $rise_fall_stat['r'] ?? 0;
        $res['fall']         = $rise_fall_stat['f'] ?? 0;
        $res['ping']         = $rise_fall_stat['p'] ?? 0;

        // 当日实时数据
        $cache_name = 'getMarketData';
        Cache::tags(['stock_fund'])->put($cache_name, $res, 60 * 60 * 24);


        // 当日实时资金数据
        $cache_name_fund = 'getMarketData_fund';
        $t = time();
        if (Cache::has($cache_name_fund)) {
            $fund = Cache::tags(['stock_fund'])->get($cache_name_fund);
            $fund = array_merge($fund, [[$t, $res['tradeAmount']]]);
        } else {
            $fund = [];
            $fund = array_merge($fund, [[$t, $res['tradeAmount']]]);
        }
        Cache::tags(['stock_fund'])->put($cache_name_fund, $fund, 60 * 60 * 24);

        // 当日实时涨跌停数据
        // $cache_name_rise = 'getMarketData_rise';
        //
        // if (Cache::has($cache_name_fund)) {
        //     $fund = Cache::get($cache_name_fund);
        //     $fund = array_merge($fund, [[$t, $res['tradeAmount']]]);
        // } else {
        //     $fund = [];
        //     $fund = array_merge($fund, [[$t, $res['tradeAmount']]]);
        // }
        // Cache::tags(['stock_fund'])->put($cache_name_fund, $fund, 60 * 60 * 24);

        return $res;
    }

    /**
     * @param $date
     * @return array|mixed
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/7/5  15:04
     */
    public function continuousLimitUp($date)
    {
        $url  = 'https://data.10jqka.com.cn/dataapi/limit_up/continuous_limit_up?filter=HS,GEM2STAR&date=' . $date;
        $data = curl($url);
        $data = json_decode($data, true);
        $data =  $data['datas'] ?? [];

        $res['data']  = $data['data'];
        $res['count'] = count($data['data']);

        return $res;
    }

    /**
     * @param $data
     * @param $ele
     * @param string $keys
     * @return array
     * @Depiction 数据初始化
     * @Author hwy <429208948@qq.com>
     * @Date 2022/4/24  16:05
     */
    private function toolInitYnData($data, $ele, $keys = 'date')
    {
        foreach ($data[$keys] as $k => $val) {
            $res_data[$val] = $data[$ele][$k];
        }

        return $res_data;
    }

    /**
     * @param string $key
     * @param int $t
     * @return mixed
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/7/5  15:13
     */
    public function fundDetailChartsByEniu(string $key, int $t = 120)
    {
        $fund_url  = 'https://eniu.com/fundDetailCharts/' . $key . '/c/' . $t;
        $fund_data = curl($fund_url);
        $fund_data = json_decode($fund_data, true);
        $fundData  = $this->toolInitYnData($fund_data, 'dwjz', 'jzrq');
        return $fundData;
    }

    public function addDataByEniu(){
        $url        = 'https://eniu.com/static/data/stock_list.json';
        $stock_list = curl($url);
        $stock_list = json_decode($stock_list, true);
        foreach ($stock_list as &$value) {
            $value['created_at'] = $value['updated_at'] = Carbon::now()->toDateTimeString();
        }

        return $stock_list;
    }

    public function perDataByEniu(string $key, int $t = 120)
    {
        if (substr($key, 0, 1) == 0) {
            $keys = 'sz' . $key;
        } else {
            $keys = 'sh' . $key;
        }

        // 市盈率 per
        // 参数：3/6/12/60/120/all
        // $pea_url = 'https://eniu.com/chart/pea/sh600584/t/60';
        $pea_url     = 'https://eniu.com/chart/pea/' . $keys . '/t/' . $t;
        $yn_pea_data = curl($pea_url);
        $yn_pea_data = json_decode($yn_pea_data, true);

        $date   = array_unique($yn_pea_data['date']);
        $price  = $this->toolInitYnData($yn_pea_data, 'price');
        $pe_ttm = $this->toolInitYnData($yn_pea_data, 'pe_ttm');

        // 市净率 pea
        // 参数：3/6/12/60/120/all
        // $pba_url = 'https://eniu.com/chart/pba/sh600584/t/60';
        $pba_url     = 'https://eniu.com/chart/pba/' . $keys . '/t/' . $t;
        $yn_pba_data = curl($pba_url);
        $yn_pba_data = json_decode($yn_pba_data, true);
        $pb          = $this->toolInitYnData($yn_pba_data, 'pb');

        // 股息率 dva
        // 参数：3/6/12/60/120/all
        // $dva_url = https://eniu.com/chart/dva/sh601318/t/12
        $dva_url     = 'https://eniu.com/chart/dva/' . $keys . '/t/' . $t;
        $yn_dva_data = curl($dva_url);
        $yn_dva_data = json_decode($yn_dva_data, true);
        $dv          = $this->toolInitYnData($yn_dva_data, 'dv');

        foreach ($date as $k => $value) {
            $stockYnData[$value]['stock_id'] = $key;
            $stockYnData[$value]['date']     = $value;
            $stockYnData[$value]['price']    = $price[$value] ?? 0;
            $stockYnData[$value]['pe']       = $pe_ttm[$value] ?? 0;
            $stockYnData[$value]['pb']       = $pb[$value] ?? 0;
            $stockYnData[$value]['dv']       = $dv[$value] ?? 0;
        }

        return $stockYnData;
    }



    /**
     * @return bool
     * @Depiction
     * @Author hwy <429208948@qq.com>
     * @Date 2022/7/1  16:39
     */
    public function addPeDataReal($stock_data = [])
    {

        $list = ''; //查询列表
        foreach ($stock_data as $key => $value) {
            if (substr($key, 0, 1) == 0) {
                $cap_pre = 'sz';
            } else {
                $cap_pre = 'sh';
            }
            $list = $list . ',' . $cap_pre . $key;
        }

        $list      = ltrim($list, ",");
        $stock_url = 'http://qt.gtimg.cn/q=' . $list;

        $stock_data = curl($stock_url);
        $stock_data = iconv("gb2312", "utf-8//IGNORE", $stock_data);
        $stock_data = explode(';', $stock_data);
        array_pop($stock_data);

        $data_list = $stock_data;

        $return_data = [];
        foreach ($data_list as $key => $val) {
            if (!empty($val)) {
                $return_data[$key] = explode('~', $val);
            }
        }

        $data = $return_data;

        $today       = Carbon::today()->toDateTimeString();
        $insertDatas = [];
        foreach ($data as $val) {
            $insertData['stock_id'] = $val[2];
            $insertData['date']     = $today;
            $insertData['price']    = $val[3] ?? 0;
            $insertData['pe']       = $val[39] ?? 0;
            $insertData['pb']       = $val[46] ?? 0;
            $insertData['dv']       = $val[64] ?? 0;

            $insertDatas[] = $insertData;
        }

        return $insertDatas;

    }

    public function getFund($key, $t){

        /*
         * f135 主力流入
         * f136 主力流出
         * f137 主力净流向
         * f138 超大单流入
         * f139 超大单流出
         * f140 超大净
         * f141 f142 f143 大单
         * f144 f145 f146 中单
         * f147 f148 f149 小单
         * f178 近五日主力增减持仓
         */
        $params = 'f135,f136,f137,f138,f139,f140,f141,f142,f143,f144,f145,f146,f147,f148,f149,f178';
        if (substr($key, 0, 1) == 0) {
            $lists = curl('https://push2.eastmoney.com/api/qt/stock/get?secid=0.' . $key . '&fields=' . $params);
        } else {
            $lists = curl('https://push2.eastmoney.com/api/qt/stock/get?secid=1.' . $key . '&fields=' . $params);
        }
        if (empty($lists)) {
            return true;
        }

        $lists = json_decode($lists, true);

        $cache_data['key']   = $key;
        $cache_data['cddlr'] = $lists['data']['f138'];
        $cache_data['cddlc'] = $lists['data']['f139'];
        $cache_data['cddje'] = $lists['data']['f140'];

        $cache_data['ddlr'] = $lists['data']['f141'];
        $cache_data['ddlc'] = $lists['data']['f142'];
        $cache_data['ddje'] = $lists['data']['f143'];

        $cache_data['zdlr'] = $lists['data']['f144'];
        $cache_data['zdlc'] = $lists['data']['f145'];
        $cache_data['zdje'] = $lists['data']['f146'];

        $cache_data['xdlr'] = $lists['data']['f147'];
        $cache_data['xdlc'] = $lists['data']['f148'];
        $cache_data['xdje'] = $lists['data']['f149'];

        $cache_data['zlc'] = $lists['data']['f135'];
        $cache_data['zlr'] = $lists['data']['f136'];
        $cache_data['je']  = $lists['data']['f137'];

        $cache_data['zjzj'] = $lists['data']['f137'];//主力增减

        // 当日数据汇总
        $cache_name_stock_cap = 'stock_cap_' . $key;
        if (Cache::has($cache_name_stock_cap)) {
            $stock_cap = Cache::tags(['my_stock_fund'])->get($cache_name_stock_cap);
            $stock_cap = array_merge($stock_cap, [[$t, $cache_data]]);
        } else {
            $stock_cap = [];
            $stock_cap = array_merge($stock_cap, [[$t, $cache_data]]);
        }
        Cache::tags(['my_stock_fund'])->put($cache_name_stock_cap, $stock_cap, 60 * 60 * 12);

        // 实时数据
        $cache_name_stock_cap_real_time = 'stock_cap_real_time_' . $key;
        Cache::tags(['my_stock_fund'])->put($cache_name_stock_cap_real_time, $cache_data, 60 * 10);
    }

}
